package com.example.demo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.JwtTokenUtils;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private UserDao userDao;

    public void add(User user) {
        if (user.getUsername() == null || "".equals(user.getUsername()))
            throw new CustomException("用户名不能为空");
        User user1 = userDao.findByName(user.getUsername());
        if (user1 != null)
            throw new CustomException("用户名已经存在，请勿重复添加");
        if (user.getPassword() == null)
            throw new CustomException("密码不能为空");
        userDao.insert(user);
    }

    public User login(User user) {
        if (user.getUsername() == null || "".equals(user.getUsername()))
            throw new CustomException("用户名不能为空");
        if (user.getPassword() == null || "".equals(user.getPassword()))
            throw new CustomException("密码不能为空");
        User user1 = userDao.findByNameAndPassword(user.getUsername(), user.getPassword());
        if (user1 == null) {
            throw new CustomException("用户名或密码输入错误");
        }
        String token = JwtTokenUtils.genToken(user1.getUsername(), user1.getPassword());
        System.out.println(token);
        user1.setAccessToken(token);
        return user1;
    }

    public User findByById(Integer id) {
        return userDao.findById(id);
    }
    public User findByName(String name) {
        return userDao.findByName(name);
    }
}
